'''
注: 网站源代码不存在M3U8 文件

流程:
    1. 拿到页面源代码
    2. 提取M3U8 的url
    3. 下载M3U8
    4. 读取M3U8 文件, 下载视频
    5. 合并视频
'''
import requests
import re


# 发送请求
url = "https://www.maihoe.com/vodplay/71591-1-1.html"
head = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 Edg/133.0.0.0"
}
# # 获取请求
# resp = requests.get(url, headers=head)
#
# # 提取M3U8 链接
# obj = re.compile(r'","url_next":"(?P<link>.*?)","from":"', re.S)
# m3u8_url = obj.search(resp.text).group("link").replace("\/", "/")
# resp.close()

# 下载M3U8 文件
# resp2 = requests.get("https://v9.tlkqc.com/wjv9/202309/12/5Cbffv7wsK1/video/1000k_720/hls/index.m3u8", headers=head)
# # 存入文件中
# with open("三叉戟.m3u8", mode="wb") as f:
#     f.write(resp2.content)
#
# resp2.close()
# print("下载完毕")


# 解析M3U8 文件
count = 1
with open("三叉戟.m3u8", mode="r", encoding="utf-8") as f:
    for line in f:
        line = line.strip()  # 去掉空格, 空白和换行
        if line.startswith("#"):  # 以 '#' 开头的不要
            continue

        # 下载视频片段
        resp3 = requests.get(line)
        f = open(f"video/{count}.ts", mode="wb")
        f.write(resp3.content)
        print(f"完成第{count}个")
        count += 1
        f.close()
        resp3.close()


